import React, { useState, useEffect } from 'react';
import { LeftOutline } from 'antd-mobile-icons';
import style from '../Lyf/VipPage.module.css';
import { useNavigate } from 'react-router-dom';
import img from '../Lyf/img/1.jpg';
import { Dialog, Popup, Toast } from 'antd-mobile';
import axios from 'axios';
import Skeleton from 'react-loading-skeleton';
import 'react-loading-skeleton/dist/skeleton.css';

export default function VipPage() {
    const navigate = useNavigate();
    const [selectedPriceOption, setSelectedPriceOption] = useState(null);
    const [loading, setLoading] = useState(false);
    const [activeTab, setActiveTab] = useState('普通会员');
    const [currentMember, setCurrentMember] = useState(() => {
        const savedMember = localStorage.getItem('currentMember');
        return savedMember ? JSON.parse(savedMember) : null;
    });
    const [paymentVisible, setpaymentVisible] = useState(false);
    const [activeWeek, setActiveWeek] = useState(1); // 当前选中的周数
    const [coupons, setCoupons] = useState([]);

    const [bankPaymentVisible, setBankPaymentVisible] = useState(false);
    const [password, setPassword] = useState('');
    const [passwordError, setPasswordError] = useState(false);

    const [isLoading, setIsLoading] = useState(true);
    useEffect(() => {
        // 模拟数据加载
        const timer = setTimeout(() => {
          setIsLoading(false);
        }, 2000);
        
        return () => clearTimeout(timer);
      }, []);

    const [paymentMethods, setPaymentMethods] = useState([
        { 
            id: 1, 
            name: '支付宝', 
            selected: true, 
            icon: '支',
            type: 'alipay' // 新增字段标识支付类型
        },
        { 
            id: 2, 
            name: '储蓄银行卡支付', 
            description: '(1886)', 
            icon: '银',
            type: 'bank'
        },
        { 
            id: 3, 
            name: '找亲友帮忙付', 
            icon: '友',
            type: 'friend'
        },
    ]);

    // 会员价格选项
    const priceOptions = {
        '普通会员': [
            { id: 1, duration: '连续包月', price: '200', originalPrice: '320', value: 'month' },
            { id: 2, duration: '连续包季', price: '400', originalPrice: '550', value: 'quarter' },
            { id: 3, duration: '12个月', price: '800', originalPrice: '900', value: 'year', recommended: true }
        ],
        '黄金会员': [
            { id: 4, duration: '连续包月', price: '300', originalPrice: '450', value: 'month' },
            { id: 5, duration: '连续包季', price: '600', originalPrice: '800', value: 'quarter' },
            { id: 6, duration: '12个月', price: '1200', originalPrice: '1500', value: 'year', recommended: true }
        ]
    };

    // 会员特权
    const privileges = {
        '普通会员': [
            { icon: '💰', text: '商品佣金' },
            { icon: '🎫', text: '4张优惠券' },
            { icon: '🚚', text: '运费免费' }
        ],
        '黄金会员': [
            { icon: '💰', text: '高额佣金' },
            { icon: '🎁', text: '专属礼包' },
            { icon: '🚀', text: '极速配送' },
            { icon: '🔒', text: '专属客服' }
        ]
    };

    // 每周优惠券数据
    const weeklyCoupons = {
        1: [
            { id: 1, amount: 5, title: '无门槛使用', status: 'used', minAmount: 0 },
            { id: 2, amount: 2, title: '满30可用', status: 'available', minAmount: 30 }
        ],
        2: [
            { id: 3, amount: 8, title: '满50减8', status: 'available', minAmount: 50 },
            { id: 4, amount: 15, title: '满100减15', status: 'available', minAmount: 100 }
        ],
        3: [
            { id: 5, amount: 10, title: '满80减10', status: 'used', minAmount: 80 },
            { id: 6, amount: 20, title: '满150减20', status: 'available', minAmount: 150 }
        ],
        4: [
            { id: 7, amount: 12, title: '满100减12', status: 'available', minAmount: 100 },
            { id: 8, amount: 25, title: '满200减25', status: 'available', minAmount: 200 }
        ]
    };

    // 处理银行卡支付
    const handleBankPayment = () => {
        setBankPaymentVisible(true);
    };
    
    // 验证密码
    const verifyPassword = () => {
        if (password.length !== 6) {
          setPasswordError(true);
          return;
        }
        
        setLoading(true);
        setTimeout(() => {
          setLoading(false);
          setBankPaymentVisible(false);
          
          // 获取选中的套餐和支付方式
          const selectedOption = priceOptions[activeTab][selectedPriceOption];
          
          // 更新会员数据
          const updatedMember = updateMemberData({
            amount: parseInt(selectedOption.price),
            duration: selectedOption.value,
            memberType: activeTab
          });
          
          setCurrentMember(updatedMember);
          
          // 显示支付成功提示
          Dialog.alert({
            content: `支付成功！\n本次充值: ¥${selectedOption.price}\n累计充值: ¥${updatedMember.totalAmount}\nVIP等级: ${updatedMember.vipLevel}`,
            confirmText: '确定'
          });
          
          setPassword('');
          setPasswordError(false);
        }, 1500);
      };

    useEffect(() => {
        // 初始化时加载第一周的优惠券
        setCoupons(weeklyCoupons[1]);
    }, []);

    const handleSubscribe = () => {
        if (selectedPriceOption === null) {
            Dialog.alert({
                content: '请选择会员套餐',
                confirmText: '确定'
            });
            return;
        }
        setpaymentVisible(true);
    };

    const formatDate = (dateString) => {
        if (!dateString) return '';
        const date = new Date(dateString);
        return `${date.getFullYear()}.${(date.getMonth() + 1).toString().padStart(2, '0')}.${date.getDate().toString().padStart(2, '0')} 到期`;
    };

    const handlePriceOptionClick = (index) => {
        setSelectedPriceOption(index === selectedPriceOption ? null : index);
    };

    const handleTabClick = (tabName) => {
        setActiveTab(tabName);
        setSelectedPriceOption(null);
    };

    // 处理支付确认
    const handlePaymentConfirm = async () => {
        setLoading(true);
        try {
            const selectedOption = priceOptions[activeTab][selectedPriceOption];
            const selectedPaymentMethod = paymentMethods.find(method => method.selected);
            
            if (selectedPaymentMethod.type === 'bank') {
                setpaymentVisible(false); // 隐藏Popup
                setBankPaymentVisible(true); // 显示密码输入Dialog
                return;
            }

            if (selectedPaymentMethod.type === 'alipay') {
                const response = await axios.post('http://localhost:3000/alipay', {
                    outTradeNo: Date.now(),
                    subject: `${activeTab}(${selectedOption.duration})`,
                    totalAmount: selectedOption.price
                });
                
                // 准备会员数据
                const memberData = {
                    memberType: activeTab,
                    amount: parseInt(selectedOption.price),
                    duration: selectedOption.value
                };
                
                // 保存到本地存储（等待支付宝回调后正式更新）
                localStorage.setItem('pendingMember', JSON.stringify(memberData));
                
                // 提交支付宝表单
                const div = document.createElement('div');
                div.innerHTML = response.data;
                document.body.appendChild(div);
                document.forms[0].submit();
                
                return;
            }
            
            // 其他支付方式
            const response = await axios.post('http://localhost:3000/member', {
                amount: parseInt(selectedOption.price),
                duration: selectedOption.value,
                memberType: activeTab,
                paymentMethod: selectedPaymentMethod.name
            });
            
            if (response.data.code === 200) {
                // 使用更新后的updateMemberData函数
                const updatedMember = updateMemberData({
                    amount: parseInt(selectedOption.price),
                    duration: selectedOption.value,
                    memberType: activeTab
                });
                
                setCurrentMember(updatedMember);
                setpaymentVisible(false);
                Dialog.alert({
                    content: `支付成功！\n本次充值: ¥${selectedOption.price}\n累计充值: ¥${updatedMember.totalAmount}\nVIP等级: ${updatedMember.vipLevel}`,
                    confirmText: '确定'
                });
            }
        } catch (error) {
            console.error('支付失败:', error);
            Dialog.alert({
                content: '支付失败，请重试',
                confirmText: '确定'
            });
        } finally {
            setLoading(false);
        }
    };

    // 检查支付宝回调
    useEffect(() => {
        const queryParams = new URLSearchParams(window.location.search);
        const isAlipaySuccess = queryParams.has('out_trade_no');
        
        if (isAlipaySuccess) {
            const pendingMember = JSON.parse(localStorage.getItem('pendingMember'));
            if (pendingMember) {
                // 使用更新后的updateMemberData函数
                const updatedMember = updateMemberData(pendingMember);
                setCurrentMember(updatedMember);
                
                Dialog.alert({
                    content: `支付成功！\n本次充值: ¥${pendingMember.amount}\n累计充值: ¥${updatedMember.totalAmount}\nVIP等级: ${updatedMember.vipLevel}`,
                    confirmText: '确定'
                });
                
                localStorage.removeItem('pendingMember');
                window.history.replaceState({}, document.title, window.location.pathname);
            }
        }
    }, []);


    // 切换周数
    const handleWeekChange = (week) => {
        setActiveWeek(week);
        setCoupons(weeklyCoupons[week]);
    };

    // 领取优惠券
    const handleClaimCoupon = (couponId) => {
        const updatedCoupons = coupons.map(coupon => {
            if (coupon.id === couponId && coupon.status === 'available') {
                return { ...coupon, status: 'claimed' };
            }
            return coupon;
        });
        setCoupons(updatedCoupons);
        Toast.show({
            content: '优惠券领取成功',
            position: 'bottom'
        });
    };

    // 初始化会员数据
    const initMemberData = () => {
        const savedMember = localStorage.getItem('currentMember');
        if (!savedMember) {
            return {
                memberType: '',
                vipLevel: 0,
                expireDate: '',
                totalAmount: 0, // 新增：累计充值金额
                transactions: [] // 新增：充值记录
            };
        }
        return JSON.parse(savedMember);
    };

    // 更新会员数据
    const updateMemberData = (newData) => {
        // 从本地存储获取现有数据
        const existingData = JSON.parse(localStorage.getItem('currentMember')) || {
            memberType: '',
            vipLevel: 0,
            expireDate: '',
            totalAmount: 0,
            transactions: []
        };

        // 计算新的到期时间（如果是续费）
        let newExpireDate = new Date();
        if (existingData.expireDate && new Date(existingData.expireDate) > new Date()) {
            // 如果当前会员未过期，则在当前到期时间基础上延长
            newExpireDate = new Date(existingData.expireDate);
        }

        // 根据套餐类型计算新的到期时间
        if (newData.duration === 'month') {
            newExpireDate.setMonth(newExpireDate.getMonth() + 1);
        } else if (newData.duration === 'quarter') {
            newExpireDate.setMonth(newExpireDate.getMonth() + 3);
        } else if (newData.duration === 'year') {
            newExpireDate.setFullYear(newExpireDate.getFullYear() + 1);
        }

        // 创建更新后的数据对象
        const updatedData = {
            ...existingData,
            memberType: newData.memberType,
            expireDate: newExpireDate.toISOString(),
            totalAmount: (existingData.totalAmount || 0) + (newData.amount || 0),
            transactions: [
                ...(existingData.transactions || []),
                {
                    amount: newData.amount,
                    date: new Date().toISOString(),
                    type: newData.memberType,
                    duration: newData.duration
                }
            ]
        };

        // 根据累计金额自动升级VIP等级
        if (updatedData.totalAmount >= 4000) {
            updatedData.vipLevel = 5;
        } else if (updatedData.totalAmount >= 2300) {
            updatedData.vipLevel = 4;
        } else if (updatedData.totalAmount >= 1200) {
            updatedData.vipLevel = 3;
        } else if (updatedData.totalAmount >= 600) {
            updatedData.vipLevel = 2;
        } else if (updatedData.totalAmount > 0) {
            updatedData.vipLevel = 1;
        }

        // 保存到本地存储
        localStorage.setItem('currentMember', JSON.stringify(updatedData));
        return updatedData;
    };



    return (
        <div>
            {isLoading ? (
                <div className={style.skeletonContainer}>
                    {/* 用户信息区域 */}
                    <div className={style.skeletonUserInfo}>
                    <div className={`${style.skeletonItem} ${style.skeletonAvatar}`}></div>
                    <div className={style.skeletonText}>
                        <div className={`${style.skeletonItem}`} style={{width: '60%', height: 20, marginBottom: 10}}></div>
                        <div className={`${style.skeletonItem}`} style={{width: '80%', height: 16}}></div>
                    </div>
                    </div>
                    
                    {/* 会员选项卡 */}
                    <div className={style.skeletonTabs}>
                    <div className={`${style.skeletonItem} ${style.skeletonTab}`}></div>
                    <div className={`${style.skeletonItem} ${style.skeletonTab}`}></div>
                    </div>
                    
                    {/* 特权区域 */}
                    <div style={{display: 'flex', justifyContent: 'space-around', marginBottom: 20}}>
                    {[1, 2, 3].map(item => (
                        <div key={item} style={{textAlign: 'center'}}>
                        <div className={`${style.skeletonItem}`} style={{width: 30, height: 30, borderRadius: '50%', margin: '0 auto 5px'}}></div>
                        <div className={`${style.skeletonItem}`} style={{width: 60, height: 16}}></div>
                        </div>
                    ))}
                    </div>
                    
                    {/* 价格选项 */}
                    {[1, 2, 3].map(item => (
                    <div key={item} className={`${style.skeletonItem}`} style={{height: 80, marginBottom: 10}}></div>
                    ))}
                    
                    {/* 按钮 */}
                    <div className={`${style.skeletonItem}`} style={{height: 50, marginTop: 20}}></div>
                </div>
                ) : (
                    <div className={style.vipContainer}>
                    {/* 顶部导航栏 */}
                    <div className={style.header}>
                        <LeftOutline className={style.backIcon} onClick={() => navigate('/my')} />
                        <h1 className={style.title}>会员</h1>
                    </div>
                    
                    {/* 用户信息区域 */}
                    <div className={style.userInfo}>
                        <div className={style.avatarContainer}>
                            {currentMember?.vipLevel > 0 ? (
                                /* VIP会员头像框 */
                                <div className={style.vipAvatarContainer}>
                                {/* VIP发光效果层 */}
                                <div className={style.vipGlow}></div>
                                
                                {/* VIP头像 */}
                                <img src={img} alt="用户头像" className={style.vipAvatar} />
                                
                                {/* VIP标识 */}
                                <div className={style.vipBadge}>
                                    {currentMember.vipLevel}
                                </div>
                                </div>
                            ) : (
                                /* 普通用户头像 */
                                <img src={img} alt="用户头像" className={style.avatar} />
                            )}
                        </div>
                        <div className={style.userDetail}>
                            <div className={style.username}>
                                张三
                                {currentMember && currentMember.vipLevel > 0 && (
                                    <span className={style.memberType}>
                                        VIP{currentMember.vipLevel}
                                    </span>
                                )}
                            </div>
                            <div className={style.memberInfo}>
                                {currentMember ? (
                                    <>
                                        <span className={style.expireDate}>
                                            {formatDate(currentMember.expireDate)}
                                        </span>
                                        {/* <span className={style.totalAmount}>
                                            累计充值: ¥{currentMember.totalAmount || 0}
                                        </span> */}
                                    </>
                                ) : (
                                    <span className={style.expireDate}>未开通会员</span>
                                )}
                            </div>
                        </div>
                        <div className={style.actionButtons}>
                            <div 
                                className={style.purchaseRecord}
                            >
                                购买记录 &gt;
                            </div>
                            <button className={style.renewButton}>立即续费</button>
                        </div>
                    </div>

                    
                    {/* 会员类型选项卡 */}
                    <div className={style.memberTabs}>
                        <div 
                            className={`${style.tabItem} ${activeTab === '普通会员' ? style.active : ''}`}
                            onClick={() => handleTabClick('普通会员')}
                        >
                            普通会员
                        </div>
                        <div 
                            className={`${style.tabItem} ${activeTab === '黄金会员' ? style.active : ''}`}
                            onClick={() => handleTabClick('黄金会员')}
                        >
                            黄金会员
                        </div>
                    </div>
                    
                    {/* 支付弹窗 */}
                    <Popup
                        visible={paymentVisible}
                        onClose={() => ss(false)}
                        position="bottom"
                        bodyStyle={{
                            borderTopLeftRadius: '8px',
                            borderTopRightRadius: '8px',
                            minHeight: '60vh'
                        }}
                    >
                        <div className={style.paymentPopup}>
                            <div className={style.paymentHeader}>
                                <div className={style.paymentAmount}>
                                    ¥{selectedPriceOption !== null ? priceOptions[activeTab][selectedPriceOption].price : '0'}
                                </div>
                                <div className={style.paymentTitle}>选择支付方式</div>
                            </div>
                            
                            <div className={style.paymentMethods}>
                                {paymentMethods.map((method) => (
                                    <div 
                                        key={method.id} 
                                        className={style.paymentMethod}
                                        onClick={() => {
                                            const updatedMethods = paymentMethods.map(m => ({
                                                ...m,
                                                selected: m.id === method.id
                                            }));
                                            setPaymentMethods(updatedMethods);
                                        }}
                                    >
                                        <div className={style.methodLeft}>
                                            <span className={style.methodIcon}>{method.icon}</span>
                                            <div className={style.methodInfo}>
                                                <div className={style.methodName}>{method.name}</div>
                                                {method.description && (
                                                    <div className={style.methodDescription}>{method.description}</div>
                                                )}
                                            </div>
                                        </div>
                                        <div className={style.methodRadio}>
                                            <input 
                                                type="radio" 
                                                checked={method.selected}
                                                readOnly
                                            />
                                        </div>
                                    </div>
                                ))}
                            </div>
                            
                            <div className={style.paymentFooter}>
                                <button 
                                    className={style.paymentConfirmButton}
                                    onClick={handlePaymentConfirm}
                                    disabled={loading}
                                >
                                    {loading ? '处理中...' : '确认支付'}
                                </button>
                            </div>
                        </div>
                    </Popup>

                    {/* 修改密码输入Dialog部分 */}
                    <Dialog
                    visible={bankPaymentVisible}
                    title="储蓄银行卡支付"
                    content={
                        <div className={style.passwordDialog}>
                        <div className={style.passwordInput}>
                            {[0, 1, 2, 3, 4, 5].map((i) => (
                            <div 
                                key={i} 
                                className={style.passwordDot}
                                onClick={() => {
                                // 点击时聚焦到隐藏的输入框
                                document.getElementById('passwordInput')?.focus();
                                }}
                            >
                                {password.length > i ? '•' : ''}
                            </div>
                            ))}
                        </div>
                        {/* 添加隐藏的输入框实际接收输入 */}
                        <input
                            id="passwordInput"
                            type="number"
                            value={password}
                            onChange={(e) => {
                            // 限制6位数字
                            const val = e.target.value.slice(0, 6);
                            setPassword(val);
                            setPasswordError(false);
                            }}
                            style={{
                            position: 'absolute',
                            opacity: 0,
                            height: 0,
                            width: 0
                            }}
                            autoFocus
                        />
                        {passwordError && (
                            <div className={style.errorMessage}>请输入6位数字密码</div>
                        )}
                        <div className={style.keyboard}>
                            {[1, 2, 3, 4, 5, 6, 7, 8, 9, '', 0, 'X'].map((key) => (
                            <button
                                key={key}
                                className={style.key}
                                onClick={() => {
                                if (key === 'X') {
                                    setPassword(prev => prev.slice(0, -1));
                                } else if (typeof key === 'number') {
                                    // 限制最多6位
                                    if (password.length < 6) {
                                    setPassword(prev => prev + key);
                                    }
                                }
                                }}
                            >
                                {key}
                            </button>
                            ))}
                        </div>
                        </div>
                    }
                    actions={[
                        [
                        {
                            key: 'cancel',
                            text: '取消',
                            onClick: () => {
                            setBankPaymentVisible(false);
                            setPassword('');
                            setPasswordError(false);
                            },
                        },
                        {
                            key: 'confirm',
                            text: '确认支付',
                            disabled: password.length !== 6,
                            onClick: verifyPassword,
                        },
                        ],
                    ]}
                    />
                    
                    {/* 尊享特权区域 */}
                    <div className={style.privilegeSection}>
                        <h3 className={style.sectionTitle}>尊享特权</h3>
                        <div className={style.privilegeList}>
                            {privileges[activeTab].map((privilege, index) => (
                                <div className={style.privilegeItem} key={index}>
                                    <div className={style.privilegeIcon}>{privilege.icon}</div>
                                    <div className={style.privilegeText}>{privilege.text}</div>
                                </div>
                            ))}
                        </div>
                    </div>
                    
                    {/* 会员价格选项 */}
                    <div className={style.priceSection}>
                        {priceOptions[activeTab].map((option, index) => (
                            <div 
                                key={option.id}
                                className={`${style.priceOption} 
                                        ${option.recommended ? style.recommended : ''} 
                                        ${selectedPriceOption === index ? style.selected : ''}`}
                                onClick={() => handlePriceOptionClick(index)}
                            >
                                <div className={style.duration}>{option.duration}</div>
                                <div className={style.price}>￥{option.price}</div>
                                <div className={style.del}><del>￥{option.originalPrice}</del></div>
                                {option.recommended && <div className={style.recommendTag}>推荐</div>}
                            </div>
                        ))}
                    </div>
                    
                    {/* 立即开通按钮 */}
                    <button 
                        className={style.subscribeButton} 
                        onClick={handleSubscribe}
                        disabled={loading}
                    >
                        {loading ? '处理中...' : '立即开通'}
                    </button>
                    
                    {/* 协议链接 */}
                    <div className={style.agreementLinks}>
                        《XX会员协议》、《自动续费服务协议》、《价格说明》
                    </div>
                    
                    {/* 仅普通会员显示优惠券区域 */}
                    {activeTab === '普通会员' && (
                        <div className={style.couponSection}>
                            <div className={style.adMemberContainer}>
                                <div className={style.adMemberBox}>
                                    <div className={style.adMemberIcon}>🎁</div>
                                    <div className={style.adMemberContent}>
                                        <div className={style.adMemberTitle}>看广告免费领会员</div>
                                        <div className={style.adMemberDesc}>观看30秒广告即可领取1天会员</div>
                                    </div>
                                    <button className={style.adMemberButton} onClick={()=>navigate('/guang')}>立即领取</button>
                                </div>
                                
                                <div className={style.adMemberBox}>
                                    <div className={style.adMemberIcon}>📱</div>
                                    <div className={style.adMemberContent}>
                                        <div className={style.adMemberTitle}>赠送好友会员</div>
                                        <div className={style.adMemberDesc}>每次只能赠送1位好友</div>
                                    </div>
                                    <button className={style.adMemberButton}>立即赠送</button>
                                </div>
                            </div>

                            <div className={style.couponHeader}>
                                <h3 className={style.sectionTitle}>会员优惠券</h3>
                                <div className={style.moreLink}>更多&gt;</div>
                            </div>
                            
                            <div className={style.couponProgress}>
                                {[1, 2, 3, 4].map(week => (
                                    <div 
                                        key={week}
                                        className={`${style.weekTab} ${activeWeek === week ? style.activeWeek : ''}`}
                                        onClick={() => handleWeekChange(week)}
                                    >
                                        第{week === 1 ? '一' : week === 2 ? '二' : week === 3 ? '三' : '四'}周
                                    </div>
                                ))}
                            </div>
                            
                            <div className={style.couponInfo}>
                                本周领券时间剩余5天，每日可领1张
                            </div>
                            
                            <div className={style.couponList}>
                                {coupons.map(coupon => (
                                    <div 
                                        key={coupon.id}
                                        className={`${style.couponItem} ${coupon.status === 'used' || coupon.status === 'claimed' ? style.used : ''}`}
                                    >
                                        <div className={style.couponAmount}>￥{coupon.amount}</div>
                                        <div className={style.couponDetail}>
                                            <div className={style.couponTitle}>{coupon.title}</div>
                                            {coupon.status === 'used' || coupon.status === 'claimed' ? (
                                                <div className={style.couponStatus}>已{coupon.status === 'used' ? '使用' : '领取'}</div>
                                            ) : (
                                                <div 
                                                    className={style.couponAction}
                                                    onClick={() => handleClaimCoupon(coupon.id)}
                                                >
                                                    领取
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}
                </div>
                )}
        </div>
    );
}